import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86136
 * Date: 2025-04-21
 * Time: 18:32
 */
//1.创建一个任务
class MyTimerTask implements Comparable<MyTimerTask> {
    private Runnable task;
    private long time;

    public MyTimerTask(Runnable task,long time) {
        this.task = task;
        this.time = time;
    }

    public long getTime() {
        return time;
    }
    public void run () {
        task.run();
    }
    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);//小跟堆
    }
}
//2实现一个定时器
class MyTimer {
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private Object locker = new Object();
    //2.1实现schedule方法，将任务添加到队列中
    public void schedule (Runnable task, long delay) {
        synchronized (locker) {
            MyTimerTask timerTask = new MyTimerTask(task,System.currentTimeMillis() + delay);
            queue.offer(timerTask);
            locker.notify();
        }
    }
    //2.2创建一个线程，负责执行队列中的任务
    public MyTimer() {
        Thread t = new Thread(() -> {
            synchronized (locker) {
                while (true) {
                    try {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimerTask task = queue.peek();
                        if (System.currentTimeMillis() < task.getTime()) {
                            locker.wait(task.getTime() - System.currentTimeMillis());
                        } else {
                            task.run();
                            queue.poll();
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException();
                    }
                }
            }
        });
        t.start();
    }
}

public class Demo49 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        },3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        },2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        },1000);
    }
}
